package com.ruoyi.web.controller.system;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ruoyi.cangku.service.ICangkuService;
import com.ruoyi.gouhuoruku.service.IGouhuoRukuService;
import com.ruoyi.kucunpandian.service.IKucunpandianService;
import com.ruoyi.qianhuankuan.service.IQianhuankuanService;
import com.ruoyi.qiankuantongji.service.IQiankuantongjiService;
import com.ruoyi.xiaoshouchuku.domain.XiaoshouChuku;
import com.ruoyi.xiaoshouchuku.service.IXiaoshouChukuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.ShiroConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.CookieUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 首页 业务处理
 * 
 * @author ruoyi
 */
@Controller
public class SysIndexController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IXiaoshouChukuService xiaoshouChukuService;

    // 系统首页
    @GetMapping("/index")
    public String index(HttpServletRequest request,ModelMap mmap)
    {
        // 取身份信息
        SysUser user = getSysUser();

        //获取当前日期
//        Date date = new Date();
        //将时间格式化成yyyy-MM-dd HH:mm:ss的格式
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String today = format.format(date).split(" ")[0];



        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(300);

        String role = xiaoshouChukuService.selectRole4User(user.getUserName());


        if (role.equals("1") || role.equals("3")) {
            session.setAttribute("QuanXian","1");

            //销售出库金额
//            List<Cangku> cangkuList = cangkuService.selectCangkuAll();
//            String msg = "";
//            for (Cangku cangku : cangkuList) {
//                Double l = xiaoshouChukuService.selectXiaoshouChukuByjiner(cangku.getCangkuName(),today);
//                if (l == null) {
//                    msg += "@"+cangku.getCangkuName()+":"+"0;";
//                }else {
//                    msg += "@"+cangku.getCangkuName()+":"+l+";";
//                }
//            }
//            System.out.println("销售出库金额："+msg);
//            session.setAttribute("xiaoshouChukuJiner",msg);
//
//            //购货入库采购金额
//            String msg1 = "";
//            for (Cangku cangku : cangkuList) {
//                Long l1 = gouhuoRukuService.selectGouhuoRukuByJiner(cangku.getCangkuName(),today);
//                if (l1 == null) {
//                    msg1 += "@"+cangku.getCangkuName()+":"+"0;";
//                }else {
//                    msg1 += "@"+cangku.getCangkuName()+":"+l1+";";
//                }
//            }
//            System.out.println("采购入库金额："+msg1);
//            session.setAttribute("gouhuorukuJiner",msg1);

            //销售出库销售量
//            String msg2 = "";
//            for (Cangku cangku : cangkuList) {
//                List l2 = xiaoshouChukuService.selectXiaoshouChukuByshuliang(cangku.getCangkuName(),today);
//                if (l2 == null) {
//                    msg2 += "@"+cangku.getCangkuName()+":"+"0;";
//                }else {
//                    msg2 += "@"+cangku.getCangkuName()+":"+l2+";";
//                }
//            }
//            session.setAttribute("xiaoshouChukuByshuliang",msg2);

            //客户未付款
//            String msg3 = "";
//            List<chaxunRuselt> all = qiankuantongjiService.selectAllQiankuantongjiList2month(today);
//            System.out.println("客户未还款："+ Arrays.toString(all.toArray()));
//            for (chaxunRuselt cha:all
//                 ) {
//                msg3+=cha.toString();
//            }
//            session.setAttribute("WeiFu4KeHu",msg3);
//
//            //客户已还款
//            String msg4 = "";
//            Double all4 = qianhuankuanService.selectQianhuankuanList4PayAndQuanXian(
//                    "已付","1","",today
//            );
//            System.out.println("客户已还款："+all4);
//            session.setAttribute("YiHuan4KeHu",all4);
//
//
//
//            // 今日销量排行前10
//            List<TestResult> list = xiaoshouChukuService.selectXiaoshouChukuByshuliang(today,null);
//            final int index = 1;
//            for (int i =0; i<list.size();i++) {
//                list.get(i).setId(i + index + "");
//            }
//            System.out.println("今日销量前十："+ list);
//            session.setAttribute("Xiaoliangpaihang",list);
//
//            // 今日出勤情况
//            List<Yuangong> list1 = yuangongService.selectTodayYuangongList(today,null);
//            System.out.println("今日出勤情况："+list1);
//            session.setAttribute("Yuangong",list1);
//
//            // 近六天的进销总金额
//            // 获取今天日期转化为 yyyy-MM-dd形式
//            String endDay = format.format(date);
//
//            // 获取六天前日期
//            //创建Calendar实例
//            Calendar cal = Calendar.getInstance();
//            //设置当前时间
//            cal.setTime(date);
//            cal.add(Calendar.DATE, -5);
//            String startDay =  format.format(cal.getTime());
//
//            // 六天前至今日入库总金额  日期越早金额越在后面
//            List<String> list2 = gouhuoRukuService.selectGouhuoRuKuByDate(null, startDay,endDay);
//            System.out.println("六天前至今日入库总金额：" + list2);
//            session.setAttribute("Rukujiner",list2);
//            // 六天前至今日入库总金额   日期越早金额越在后面
//            List<String> list3 = xiaoshouChukuService.selectXiaoshouChukuByDate(null,startDay,endDay);
//            System.out.println("六天前至今日出库总金额：" + list2);
//            session.setAttribute("Chukujiner",list3);
//
//
//            // 库存比列
//            List<String> list4 = kucunpandianService.selectCangkupandianProportion();
//            System.out.println("库存比例：" + list4);
//            session.setAttribute("kucun",list4);


        }else {
            session.setAttribute("QuanXian",xiaoshouChukuService.selectRole2User(user.getUserName()));
            // 销售出库金额
//            Double l = xiaoshouChukuService.selectXiaoshouChukuByjiner(user.getUserName(),today);
//            String result = "";
//            if (l == null) {
//                result = "count:0;";
//                System.out.println("销售出库金额   "+result);
//                session.setAttribute("xiaoshouChukuJiner",result);
//            }else {
//                result = "count:"+l+";";
//                System.out.println("销售出库金额    "+result);
//                session.setAttribute("xiaoshouChukuJiner",result);
//            }
//
//            Long l1 = gouhuoRukuService.selectGouhuoRukuByJiner(user.getUserName(),today);
//            String result1 = "";
//            if (l1 == null) {
//                System.out.println("购货入库金额 0   "+result1);
//                result1 = "count:0;";
//                session.setAttribute("gouhuorukuJiner",result1);
//            }else {
//                result1 = "count:"+l1+";";
//                System.out.println("购货入库金额    "+result1);
//                session.setAttribute("gouhuorukuJiner",result1);
//            }
//            //客户未付款
//            String msg3 = "";
//            Double all = qianhuankuanService.selectQianhuankuanList4PayAndQuanXian(
//                    "未付","0",user.getUserName(),today
//            );
//            System.out.println("客户未付款   "+ all);
//
//            session.setAttribute("WeiFu4KeHu",all);
//            //客户已还款
//            String msg4 = "";
//            Double all4 = qianhuankuanService.selectQianhuankuanList4PayAndQuanXian(
//                    "已付","0",user.getUserName(),today
//            );
//            System.out.println("客户已付款   "+ all4);
//            session.setAttribute("YiHuan4KeHu",all4);
//
//
//            // =================================
//            // 今日销量排行前10
//            List<TestResult> list = xiaoshouChukuService.selectXiaoshouChukuByshuliang(today,user.getUserName());
//            final int index = 1;
//            for (int i =0; i<list.size();i++) {
//                list.get(i).setId(i + index + "");
//            }
//            System.out.println("今日销量前十："+ list);
//            session.setAttribute("Xiaoliangpaihang",list);
//
//            // 今日出勤情况
//            List<Yuangong> list1 = yuangongService.selectTodayYuangongList(today,user.getUserName());
//            System.out.println("今日出勤情况："+list1);
//            session.setAttribute("Yuangong",list1);
//
//            // 近六天的进销总金额
//            // 获取今天日期转化为 yyyy-MM-dd形式
//            String endDay = format.format(date);
//
//            // 获取六天前日期
//            //创建Calendar实例
//            Calendar cal = Calendar.getInstance();
//            //设置当前时间
//            cal.setTime(date);
//            cal.add(Calendar.DATE, -5);
//            String startDay =  format.format(cal.getTime());
//
//            // 六天前至今日入库总金额  日期越早金额越在后面
//            List<String> list2 = gouhuoRukuService.selectGouhuoRuKuByDate(user.getUserName(), startDay,endDay);
//            System.out.println("六天前至今日入库总金额：" + list2);
//            session.setAttribute("Rukujiner",list2);
//            // 六天前至今日出库总金额   日期越早金额越在后面
//            List<String> list3 = xiaoshouChukuService.selectXiaoshouChukuByDate(user.getUserName(), startDay,endDay);
//            System.out.println("六天前至今日出库总金额：" + list2);
//            session.setAttribute("Chukujiner",list3);
//
//
//            // 库存比列
//            List<String> list4 = kucunpandianService.selectCangkupandianProportion();
//            System.out.println("库存比例：" + list4);
//            session.setAttribute("kucun",list4);


        }

        session.setAttribute("name4user",user.getUserName());


        List<XiaoshouChuku> listNoDo = xiaoshouChukuService.selectXiaoshouChukuListNoDo(user.getUserName());
        if (listNoDo.size() != 0) {
            session.setAttribute("weiZhiXing","1");
        }



        /*if (user != null) {
            switch (user.){

            }
        }*/
//        QuanJuBianLiang.quanXian = user.getRemark();

        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        Boolean footer = Convert.toBool(configService.selectConfigByKey("sys.index.footer"), true);
        Boolean tagsView = Convert.toBool(configService.selectConfigByKey("sys.index.tagsView"), true);
        mmap.put("footer", footer);
        mmap.put("tagsView", tagsView);
        mmap.put("mainClass", contentMainClass(footer, tagsView));
        mmap.put("copyrightYear", RuoYiConfig.getCopyrightYear());
        mmap.put("demoEnabled", RuoYiConfig.isDemoEnabled());
        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        mmap.put("isMobile", ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")));

        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies)
        {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName()))
            {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap)
    {
        mmap.put("user", getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password)
    {
        SysUser user = getSysUser();
        if (StringUtils.isNull(user))
        {
            return AjaxResult.error("服务器超时，请重新登录");
        }
        if (passwordService.matches(user, password))
        {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin()
    {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response)
    {
        CookieUtils.setCookie(response, "nav-style", style);
    }

    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap)
    {
        mmap.put("version", RuoYiConfig.getVersion());
        return "main";
    }

    // content-main class
    public String contentMainClass(Boolean footer, Boolean tagsView)
    {
        if (!footer && !tagsView)
        {
            return "tagsview-footer-hide";
        }
        else if (!footer)
        {
            return "footer-hide";
        }
        else if (!tagsView)
        {
            return "tagsview-hide";
        }
        return StringUtils.EMPTY;
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
}
